<template>
  <div class="monitorAddWrap">
    <div class="pageTableInner">
      <el-form :model="ruleFormAdd" ref="ruleFormAdd" :rules="rulesAdd" label-width="90px" class="demo-ruleForm">
        <div class="infoSearchWrap" style="padding: 20px 20px 0px 20px;min-height: 242px;">
          <div class="infoSearchOne" style="margin-bottom: 0px;">
            <el-row :gutter="20">
              <el-col :span="7">
                <div class="searchWrap">
                  <el-form-item style="display: inline-block;width: 180px;" label="行政区域:" prop="district" :rules="[{ 'required': true, 'message': '请选择行政区', 'trigger': 'blur' }]">
                  <span class="searchInputFont" style="width: 100%;">
                    <el-select v-model="ruleFormAdd.district" @change="changeDistrict(ruleFormAdd.district)" size="mini" :disabled="$store.state.userInfo.regionId?true:false"  clearable placeholder="行政区">
                      <el-option
                        v-for="item in $store.state.districtData"
                        :key="item.id"
                        :label="item.regionName"
                        :value="item.id">
                      </el-option>
                    </el-select>
                  </span>
                  </el-form-item>
                  <el-form-item style="display: inline-block;" label-width="0px" prop="street"
                                :rules="[{ 'required': true, 'message': '请选择街道', 'trigger': 'blur' }]">
                  <span class="searchInputFont" style="width: 70%;">
                    <el-select @change="checkstreet(ruleFormAdd.street)" v-model="ruleFormAdd.street" size="mini"
                               clearable placeholder="街道">
                      <el-option
                        v-for="item in streetData"
                        :key="item.id"
                        :label="item.regionName"
                        :value="item.id">
                      </el-option>
                    </el-select>
                 </span>
                  </el-form-item>
                </div>
              </el-col>
              <el-col :span="5">
                <div class="searchWrap">
                  <el-form-item label="区域名称:" prop="areaName" :rules="[{ 'required': true, 'message': '请输入区域名称', 'trigger': 'blur' }]">
                    <el-input style="width: 100%;" size="mini" clearable v-model="ruleFormAdd.areaName" auto-complete="off" :maxlength="10" placeholder="区域名称"></el-input>
                  </el-form-item>
                </div>
              </el-col>
              <el-col :span="4">
                <div class="searchWrap">
                  <el-form-item style="display: inline-block;" label="停放容量:" prop="parkValue" :rules="[{ 'required': true, 'message': '请输入停放容量', 'trigger': 'blur' }]">
                  <span class="searchInputFont" style="width: 100%;">
                    <el-input size="mini" v-model="ruleFormAdd.parkValue" auto-complete="off" placeholder="容量(辆)"></el-input>
                   </span>
                  </el-form-item>
                </div>
              </el-col>
              <el-col :span="4">
                <div class="searchWrap">
                  <el-form-item label="状态:" prop="areaStatus" :rules="[{ 'required': true, 'message': '请输入选择状态', 'trigger': 'blur' }]">
                    <span class="searchInputFont" style="width: 100%;">
                      <el-select v-model="ruleFormAdd.areaStatus" size="mini" clearable placeholder="请选择">
                        <el-option
                         v-for="item in options1"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
                        </el-option>
                      </el-select>
                    </span>
                  </el-form-item>
                </div>
              </el-col>
              <el-col :span="4">
                <div class="searchWrap">
                  <el-form-item label="紧急程度:"  prop="urgentType" :rules="[{ 'required': true, 'message': '请选择紧急程度', 'trigger': 'blur' }]">
                    <span class="searchInputFont" style="width: 100%;">
                      <el-select v-model="ruleFormAdd.urgentType" size="mini" clearable placeholder="请选择">
                        <el-option
                         v-for="item in options2"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
                        </el-option>
                      </el-select>
                    </span>
                  </el-form-item>
                </div>
              </el-col>
            </el-row>
          </div>
          <div class="infoSearchOne" style="margin-bottom: 0px;">
            <el-row :gutter="20">
              <el-col :span="7">
                <div class="searchWrap">
                  <el-form-item label="有效期:" prop="periodBegin" :rules="[{ 'required': true, 'message': '请输入有效期时间范围', 'trigger': 'blur' }]">
                    <span class="searchInputFont" style="width: 100%;">
                      <el-date-picker
                        @change="getTimeDate"
                        v-model="value7"
                        style="width: 100%;"
                        type="daterange"
                        align="right"
                        size="mini"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        :picker-options="$store.state.pickerOptions1"
                      >
                      </el-date-picker>
                    </span>
                  </el-form-item>
                </div>
              </el-col>
              <!-- <el-col :span="5">
                <div class="searchWrap">
                  <el-form-item label="区域类型:" prop="areaType" :rules="[{ 'required': true, 'message': '请输入区域类型', 'trigger': 'blur' }]">
                    <el-select v-model="ruleFormAdd.areaType" @change="changeAlarm(ruleFormAdd.areaType)" size="mini" clearable placeholder="区域类型">
                      <el-option
                        v-for="item in options"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </div>
              </el-col> -->
              <el-col :span="5">
                <div class="searchWrap">
                  <el-form-item style="display: inline-block;" label="告警阈值:" prop="alarmValue" :rules="[{ 'required': true, 'message': '请输入告警阈值', 'trigger': 'blur' }]">
                    <span class="searchInputFont" style="width: 100%;">
                      <el-input size="mini" v-model="ruleFormAdd.alarmValue" auto-complete="off" placeholder="阈值(辆)"></el-input>
                    </span>
                  </el-form-item>
                </div>
              </el-col>
              <el-col :span="4">
                <div class="searchWrap">
                  <el-form-item label="预警次数:" prop="alarmCount" :rules="[{ 'required': true, 'message': '请选择预警次数', 'trigger': 'blur' }]">
                    <span class="searchInputFont" style="width: 100%;">
                      <el-select v-model="ruleFormAdd.alarmCount" size="mini" clearable placeholder="预警次数">
                        <el-option
                         v-for="item in options3"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
                        </el-option>
                      </el-select>
                    </span>
                  </el-form-item>
                </div>
              </el-col>
              <el-col :span="4">
                <div class="searchWrap">
                  <el-form-item label="间隔时间:" prop="monitorInterval" :rules="[{ 'required': true, 'message': '请选择间隔时间', 'trigger': 'blur' }]">
                    <span class="searchInputFont" style="width: 100%;">
                      <el-select v-model="ruleFormAdd.monitorInterval" size="mini" clearable placeholder="间隔时间">
                        <el-option
                         v-for="item in options4"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
                        </el-option>
                      </el-select>
                    </span>
                  </el-form-item>
                </div>
              </el-col>
            </el-row>
          </div>
          <div class="infoSearchOne" style="margin-bottom: 0px;">
            <el-row :gutter="20">
              <el-col :span="7">
                <div class="searchWrap">
                  <el-form-item style="display: inline-block; width: 100%;" label="详细地址:" prop="areaAddress" :rules="[{ 'required': true, 'message': '请输入详细地址', 'trigger': 'blur' }]">
                    <span class="searchInputFont" style="width: 100%;">
                      <el-input size="mini" v-model="ruleFormAdd.areaAddress" auto-complete="off" placeholder=""></el-input>
                    </span>
                  </el-form-item>
                </div>
              </el-col>
              <el-col :span="5">
                <div class="searchWrap">
                  <el-form-item style="display: inline-block;" label="面积:" prop="area" :rules="[{ 'required': true, 'message': '请输入面积', 'trigger': 'blur' }]">
                    <span class="searchInputFont" style="width: 100%;">
                      <el-input size="mini" v-model="ruleFormAdd.area" auto-complete="off" placeholder="平方米"></el-input>
                    </span>
                  </el-form-item>
                </div>
              </el-col>
              <el-col :span="5">
                <div class="searchWrap">
                  <el-form-item style="display: inline-block;" label="经纬度:">
                  <span class="searchInputFont" style="width: 100%;">
                    <el-input size="mini" auto-complete="off" :disabled="true" :value="resultShape.length>0 ? (resultShape[0].lat + ',' + resultShape[0].lng): ''"></el-input>
                   </span>
                  </el-form-item>
                </div>
              </el-col>
            </el-row>
          </div>
          <div class="infoSearchOne" style="margin-bottom: 0px;">
            <el-row :gutter="20">
              <el-form-item label="监控时段:" required>
                <el-row>
                  <el-col :span="8" v-for="(time, index) in ruleFormAdd.monitorTime" :key="index">
                    <div class="searchWrap">
                      <el-form-item
                        style="width: 32%;display: inline-block;"
                        :prop="'monitorTime.' + index + '.begin'"
                        :rules="[{ 'required':true, 'message': '请选择起始时间', 'trigger': 'blur' }]">
                        <el-time-select
                          style="width:100%;"
                          size="mini"
                          :editable="false"
                          placeholder="起始时间"
                          v-model="time.begin"
                          :picker-options="{'start': index==0?'00:00':ruleFormAdd.monitorTime[index-1].end,'step': '00:15','end': '24:00','minTime': index==0?'':ruleFormAdd.monitorTime[index-1].end }">
                        </el-time-select>
                      </el-form-item>
                      -
                      <el-form-item
                        style="width: 32%;display: inline-block;"
                        :prop="'monitorTime.' + index + '.end'"
                        :rules="[{ 'required':true, 'message': '请选择结束时间', 'trigger': 'blur' }]">
                        <el-time-select
                          style="width:100%;"
                          size="mini"
                          :editable="false"
                          placeholder="结束时间"
                          v-model="time.end"
                          :picker-options="{'start': time.begin,'step': '00:15','end': '24:00','minTime': time.begin }"
                        >
                        </el-time-select>
                        <el-button style="margin-left: 10px;" @click.prevent="removeDomain(time)" v-show="index!=0">删除</el-button>
                        <el-button v-show="index==0" @click="addDomain">新增</el-button>
                      </el-form-item>
                    </div>
                  </el-col>
                  <div style="float: right;margin-right: 10px;margin-top: 3px;">
                    <el-button type="primary" size="mini" @click="submitForm('ruleFormAdd')">提交</el-button>
                    <router-link style="margin-left: 10px;" to="/monitoringArea">
                      <el-button type="primary" size="mini">取消</el-button>
                    </router-link>
                  </div>
                </el-row>
              </el-form-item>
            </el-row>
          </div>
        </div>
      </el-form>
      <div class="mapWrap">
        <div class="containerWrap" ref="mapScreenfull">
          <div class="infoButton">
            <i @click='screenfullMap' style="font-size: 20px;" class="iconfont icon-quanping2"></i>
          </div>
          <div id="container"></div>
          <div class="mapRailButton">
            <el-button class="editor-btn" type="primary" size="mini" @click="handeldraw(1)">矩 形</el-button>
            <br/><br/>
            <el-button class="editor-btn" type="primary" size="mini" @click="handeldraw(2)">多边形</el-button>
            <br/><br/>
            <el-button class="editor-btn" type="primary" size="mini" @click="handeldraw(0)">清 除</el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>

  export default {
    props: [],
    data () {
      return {
        map: "",
        drawingManager: "",
        dioTrue: "",
        value7: "",
        resultShape: [],
        overlays: [],
        markers: [],
        ruleFormAdd: {
          monitorTime: [{begin: "", end: ""}],
          "street": "",
          district: this.$store.state.userInfo.regionId,
          "areaName":"",
          "areaType": "",
          "areaAttribute":1,
          "parkValue":"",
          "alarmValue":"",
          "alarmCount":"",
          "monitorInterval":"",
          "urgentType":"",
          "periodBegin":"",
          "periodEnd":"",
          "areaStatus": "",
          "lng":"",
          "lat":"",
          "areaPoints":""
        },
        options1: [
          {
            value: '0',
            label: '正常'
          }, {
            value: '1',
            label: '规划中'
          }, {
            value: '2',
            label: '停用'
          }],
        options2: [
          {
            value: '0',
            label: '一般'
          }, {
            value: '1',
            label: '紧急'
          }],
        options3: [
          {
            value: '1',
            label: '1次'
          }, {
            value: '2',
            label: '2次'
          }, {
            value: '3',
            label: '3次'
          }, {
            value: '4',
            label: '4次'
          }, {
            value: '5',
            label: '5次'
          }, {
            value: '6',
            label: '6次'
          }],
        options4: [
          {
            value: '10',
            label: '10分钟'
          } ,{
            value: '15',
            label: '15分钟'
          } ,{
            value: '20',
            label: '20分钟'
          } ,{
            value: '25',
            label: '25分钟'
          } ,{
            value: '30',
            label: '30分钟'
          } ,{
            value: '45',
            label: '45分钟'
          } ,{
            value: '60',
            label: '60分钟'
          }
          ],
        rulesAdd: {},
        options: [
           {
            value: '1',
            label: '禁停区'
          }, {
            value: '2',
            label: '规范停放区'
          }, {
            value: '3',
            label: '动态调节区'
          }, {
            value: '4',
            label: '临时监控区'
          }],
        streetData: [],
      }
    },

    mounted(){
      this.getRailMap()
      document.querySelector(".containerWrap").style.height = document.querySelector(".mapWrap").clientHeight - 20 + "px"
    },
    created(){
      setTimeout(()=>{
        if(this.$store.state.userInfo.regionId){this.changeDistrict(this.ruleFormAdd.district)}
      },500)
    },

    methods: {
      changeAlarm(key){
        if(key==1){
          this.ruleFormAdd.parkValue=0
          this.ruleFormAdd.alarmValue=0
        }
      },
      //添加，删除
      removeDomain(item) {
        var index = this.ruleFormAdd.monitorTime.indexOf(item)
        if (index !== -1) {
          this.ruleFormAdd.monitorTime.splice(index, 1)
        }
      },
      addDomain(){
        if(this.ruleFormAdd.monitorTime.length<5){
          this.ruleFormAdd.monitorTime.push({
            begin: '',
            end: '',
          });
        }

      },
      submitForm(formName) {
        this.ruleFormAdd.areaPoints = JSON.stringify(this.resultShape)
        let monitorTime = JSON.stringify(this.ruleFormAdd.monitorTime)
        if (this.resultShape.length == 0) {
          this.$message({
            type: 'warning',
            message: "请在地图上画区域"
          });
          this.getPoint()
          return
        }
        let latAll = 0, lngAll = 0
        this.resultShape.forEach(item => {
          latAll += item.lat
          lngAll += item.lng
        })
        this.ruleFormAdd.lng = (lngAll / this.resultShape.length).toFixed(7)
        this.ruleFormAdd.lat = (latAll / this.resultShape.length).toFixed(7)
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.axios.post(process.env.API_HOST + 'area/insertGovMonitorArea', {...this.ruleFormAdd,monitorTime:monitorTime})
              .then(response => {
                let result = response.data
                if (result.code == 200) {
                  this.$message({
                    type: 'success',
                    message: '新增成功!'
                  });
                  this.$emit("searchRowsInfo")
                  setTimeout(() => {
                    this.$router.push("/monitoringArea")
                  }, 1300)
                }

              })
              .catch(error => {
                console.log(error);
              });
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },

      getTimeDate(value){
        if (value) {
          this.ruleFormAdd.periodBegin = this.dtime(value[0]).format('YYYY-MM-DD')
          this.ruleFormAdd.periodEnd = this.dtime(value[1]).format('YYYY-MM-DD')
        } else {
          this.ruleFormAdd.periodBegin = ""
          this.ruleFormAdd.periodEnd = ""
        }
      },
      getPoint(){
        var arr = [];
        if (this.overlays.length > 1) {
          this.$message({
            type: 'warning',
            message: "地图区域单次只能增加1个"
          });
          this.dioTrue = true
        } else {
          this.dioTrue = false
          this.overlays.forEach((item) => {
            item.getPath().forEach((item2) => {
              arr.push({lat: item2.lat, lng: item2.lng})
            })
          })
        }
        this.resultShape = arr

      },
      handeldraw(index){
        if (index == 0) {//清除
          this.clearAll()
          this.resultShape = []
        } else if (index == 1) {//矩形
          this.draw(BMAP_DRAWING_RECTANGLE)
        } else if (index == 2) {//多边形
          this.draw(BMAP_DRAWING_POLYGON)
        }
      },
      screenfullMap(){
        if (this.screenfull.enabled) {
          this.screenfull.toggle(this.$refs.mapScreenfull);
        }
      },
      getLocation(name){
        if (name != "") {
          this.map.clearOverlays();
          this.map.centerAndZoom("深圳市" + name, 13);      // 用城市名设置地图中心点
        }
      },
      //获取街道
      changeDistrict(district){
        if (!district) {
          this.ruleFormAdd.street = ""
          this.streetData = []
          return
        }
        this.axios.post(process.env.API_HOST + '/common/selectRegion', {parentId: district})
          .then(response => {
            const result = response.data
            if (result.code == 200) {
              this.streetData = result.result
            }
          })

        //定位
        this.$store.state.districtData.forEach(item => {
          if (item.id == district && item.regionPoints) {
            this.getBoundary(JSON.parse(item.regionPoints))
          }
        })
      },
      //改变街道
      checkstreet(street){
        if(!this.ruleFormAdd.street){
          this.changeDistrict(this.ruleFormAdd.district)
        }
        this.streetData.forEach(item => {
          if (item.id == street && item.regionPoints) {
            this.getBoundary(JSON.parse(item.regionPoints))
          }
        })
      },
      //百度提取区域经纬度
      getBoundary(areaPoints) {
        this.clearAll()
        let _this = this, arr = []
        if (areaPoints && areaPoints.length > 2) {
          _this.map.clearOverlays();        //清除地图覆盖物
          areaPoints.forEach((item) => {
            arr.push(new BMap.Point(item.lng, item.lat))
          })
          //              Polyline  Polygon
          _this.ply = new BMap.Polyline(arr, {
            strokeColor: "#3975FE",    //边线颜色。
            fillColor: "white",      //填充颜色。当参数为空时，圆形将没有填充效果。
            strokeWeight: 1,       //边线的宽度，以像素为单位。
            strokeOpacity: 1,    //边线透明度，取值范围0 - 1。
            fillOpacity: 1,      //填充的透明度，取值范围0 - 1。
            strokeStyle: 'solid' //边线的样式，solid或dashed。
          });  //创建多边形

          _this.map.addOverlay(_this.ply);  //添加覆盖物
          _this.map.setViewport(_this.ply.getPath());    //调整视野

        }

      },
      getRailMap(){
        let _this = this
        _this.map = new BMap.Map("container", {
          enableMapClick: false,
          minZoom: 10,
          maxZoom: 19
        });          // 创建地图实例
        let pointOne = new BMap.Point(this.$store.state.userInfo.lng, this.$store.state.userInfo.lat)

        _this.map.centerAndZoom(pointOne, 19);             // 初始化地图，设置中心点坐标和地图级别
        _this.map.enableScrollWheelZoom(); // 允许滚轮缩放

        _this.map.addControl(new BMap.OverviewMapControl());
        _this.map.addControl(new BMap.NavigationControl());  //添加默认缩放平移控件
        this.map.addControl( new BMap.ScaleControl({anchor: BMAP_ANCHOR_BOTTOM_RIGHT}));
//        _this.map.addOverlay(new BMap.Marker(pointOne))

//        var overlays = [];
        var overlaycomplete = function (e) {
          _this.overlays.push(e.overlay);
          _this.getPoint()
        };
        var styleOptions = {
          strokeColor: "#3975FE",    //边线颜色。
          fillColor: "#A9CDE5",      //填充颜色。当参数为空时，圆形将没有填充效果。
          strokeWeight: 1,       //边线的宽度，以像素为单位。
          strokeOpacity: 0.8,    //边线透明度，取值范围0 - 1。
          fillOpacity: 0.6,      //填充的透明度，取值范围0 - 1。
          strokeStyle: 'solid' //边线的样式，solid或dashed。
        }

        //实例化鼠标绘制工具
        _this.drawingManager = new BMapLib.DrawingManager(_this.map, {
          isOpen: false, //是否开启绘制模式
          drawingToolOptions: {
            anchor: BMAP_ANCHOR_TOP_RIGHT, //位置
            offset: new BMap.Size(5, 5), //偏离值
          },
          polygonOptions: styleOptions, //多边形的样式
          rectangleOptions: styleOptions //矩形的样式
        });

        //添加鼠标绘制工具监听事件，用于获取绘制结果
        _this.drawingManager.addEventListener('overlaycomplete', overlaycomplete);

      },
      draw(type){
        this.drawingManager.open();
        this.drawingManager.setDrawingMode(type);

      },
      clearAll () {
        for (var i = 0; i < this.overlays.length; i++) {
          this.map.removeOverlay(this.overlays[i]);
        }
        this.overlays.length = 0
        this.drawingManager.close()
      },

    },
    watch: {
      /*lngLat(){
       this.getRailMap()
       }*/
    }
  }
</script>

<style lang="stylus" rel="stylesheet/stylus">
  @import "../../../common/stylus/mixin.styl"
  .monitorAddWrap
    page1()
    background-color #EFEEF3
    .mapWrap
      position absolute
      top 272px
      left 0px
      right 0px
      bottom 0px
      padding 10px
      box-sizing border-box
      background-color white
      border-radius 5px
      .containerWrap
        height: 100%;
        width: 100%;
        margin 0px auto;
        position: relative;
        .infoButton
          font-size: 16px;
          color: $co1;
          position: absolute;
          top: 10px;
          right: 10px;
          z-index 5
          opacity: 0;
          .iconfont
            display: inline-block;
            font-size: 20px;
            cursor pointer
        #container
          height: 100%;
          width: 100%;
        .mapRailButton
          position: absolute;
          top: 180px;
          left: 12px;
      &:hover .infoButton
        opacity: 1;

</style>
